package info.hexin.mvc.handler;

import info.hexin.log.Log;
import info.hexin.log.Logs;
import info.hexin.mvc.handler.process.DefaultRequestProcess;
import info.hexin.mvc.handler.process.FileUploadRequestProcess;
import info.hexin.mvc.handler.process.RequestProcess;
import info.hexin.mvc.handler.process.StreamUploadRequestProcess;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 请求所有处理，包括文件上传等
 * 
 * @author ydhexin@gmail.com
 * 
 */
public class RequestHandler {
    private static final Log log = Logs.get();
    
    private RequestProcess requestProcess = new DefaultRequestProcess();
    private RequestProcess fileUploadRequestProcess = new FileUploadRequestProcess();
    private RequestProcess streamUploadRequestProcess = new StreamUploadRequestProcess();

    public void handler(HttpServletRequest request, HttpServletResponse response) {
        RequestContext requestContext = new RequestContext();
        requestContext.setRequest(request).setResponse(response);
        String contentType = request.getContentType();

        if (log.isDebugEnabled()) {
            log.debug("RequestURI >>>>> {} ,contentType >>>>> {}", request.getRequestURI(), contentType);
        }

        try {
            if (contentType == null) {
                requestProcess.process(requestContext);
            } else if (contentType.contains("multipart/form-data")) {
                fileUploadRequestProcess.process(requestContext);
            } else if (contentType.contains("application/octet-stream")) {
                streamUploadRequestProcess.process(requestContext);
            } else if (contentType.contains("application/x-www-form-urlencoded")) {
                throw new RuntimeException("file upload form missing multipart/form-data");
            }
        } catch (Exception e) {
            throw new RuntimeException("file upload error!!", e);
        }
    }

    public void setRequestProcess(RequestProcess requestProcess) {
        this.requestProcess = requestProcess;
    }

    public void setFileUploadRequestProcess(RequestProcess fileUploadRequestProcess) {
        this.fileUploadRequestProcess = fileUploadRequestProcess;
    }

    public void setStreamUploadRequestProcess(RequestProcess streamUploadRequestProcess) {
        this.streamUploadRequestProcess = streamUploadRequestProcess;
    }
}
